/*
	This file is part of "Ants on the web".

    "Ants on the web" is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    "Ants on the web" is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with "Ants on the web".  If not, see <http://www.gnu.org/licenses/>.
*/

package org.utc.ia04.antsontheweb.antColonyOptimisation.ant;

import java.net.MalformedURLException;
import java.net.URL;
import java.util.Stack;

import org.utc.ia04.antsontheweb.utilities.Requete;

import jade.core.AID;
import jade.core.Agent;
import jade.domain.DFService;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;
import jade.wrapper.AgentContainer;
import jade.wrapper.AgentController;

public class AntAgent extends Agent
{
	//serialVersionUID
	private static final long serialVersionUID = 3131948631604957667L;
	
	//DF Information
	public static final String DF_TYPE = "Ant";//Plutot mettre les static en majuscules

	//Default values
	public static final long DEFAULT_LIFE_EXTANCY =100;
	public static final long DEFAULT_VARIANCE_LIFE_EXTANCY = 20;
	
	//attributes
	private int age;
	private boolean carryRessource;
	private URL antColonyUrl;
	public Stack<URL> visitedUrl; // rendre la methode privee et lui creer un accesseur
	private AID parserAID;
	private AID pathFinderAID;
	private AID antColonyAID;
	private long tickerTime;
	private long myLifeExpectancy;
	
	//methods
	public void setup()
	{
		Object[] args = getArguments();
		try
		{
			antColonyUrl = new URL(args[0].toString());
		}
		catch (MalformedURLException e1)
		{
			e1.printStackTrace();
		}

		tickerTime= (Long)args[1];
		antColonyAID = new AID(args[2].toString(),true);
		age = 0;
		carryRessource = false;
		visitedUrl = new Stack<URL>();
		visitedUrl.push(antColonyUrl);
	    AgentContainer c =  getContainerController();
	    // creation du pathFinder
		try
		{
			Object [] argsPathFinder = new Object[2];
			argsPathFinder[0] = this.getName();
			argsPathFinder[1] = antColonyUrl;
			AgentController pathFinderController = c.createNewAgent( "PathFinder_"+this.getName().split("@")[0], "org.utc.ia04.antsontheweb.antColonyOptimisation.ant.pathFinder.AntPathFinderAgent", argsPathFinder );
			pathFinderController.start();
			pathFinderAID = new AID(pathFinderController.getName(),true);
		}
		catch (Exception e){System.out.println(e.getMessage());}
	        
		// creation du parser
		try
		{
			Object [] argsParser = new Object[3];
		    argsParser[0] = this.getName();
		    argsParser[1] = pathFinderAID.getName();//
		    argsParser[2] = (Integer)args[3];
            AgentController parserController = c.createNewAgent( "Parser_"+this.getName().split("@")[0], "org.utc.ia04.antsontheweb.antColonyOptimisation.ant.parser.AntParserAgent", argsParser );
            parserController.start();
            parserAID = new AID(parserController.getName(),true);//petit hack
        }
        catch (Exception e){System.out.println("Erreur dans la creation de parser : " + e.toString());}
	    
        //addBehaviour
		addBehaviour(new AntBhv());
		register();
		 
		//on envoie le parserAID a l'agent PathFinder
		ACLMessage msg = new ACLMessage(ACLMessage.REQUEST);
		Requete query = new Requete(Requete.ANT_SENDPARSERAID,parserAID.getName().toString());
		msg.setContent(query.serialize());
		msg.addReceiver(getPathFinderAID());
		send(msg);			
		
		//lifeExpectancy
		long lifeExpectancy = (Long)args[4];
		long lifeExpectancyVar = (Long)args[5];
		
		double x1 = Math.random(), x2 = Math.random();
		myLifeExpectancy = lifeExpectancy +  (long)(Math.sqrt(-2*Math.log(x1)) * Math.cos(2*Math.PI * x2) * lifeExpectancyVar);
	}

	 // accessors
	
	int getAge ()
	{
		return age;
	}
	
	boolean getCarryRessource () { return carryRessource;}
	void setCarryRessource(boolean bool){ carryRessource = bool;}
	URL getAntColonyUrl () { return antColonyUrl;}
	void incAge(){age++;}
	
	boolean dropDead()
	{
		return myLifeExpectancy < age;
	}
	
	
	protected //clean up

	void takeDown()
	{
		ACLMessage msg = new ACLMessage(ACLMessage.REQUEST);
		Requete query = new Requete(Requete.ANT_DYING,""); msg.setContent(query.serialize());
		msg.addReceiver(getParserAID()); msg.addReceiver(getPathFinderAID()); msg.addReceiver(getAntColonyAID());
		send(msg);
	}
	
	private void register()
	{
		DFAgentDescription dfd = new DFAgentDescription();
		dfd.setName(getAID());
		ServiceDescription sd = new ServiceDescription();
		sd.setType(DF_TYPE); sd.setName(this.getName());
		dfd.addServices(sd);
		try { DFService.register(this, dfd); }
		catch (Exception fe) {}
	}

	AID getParserAID()
	{
		return parserAID;
	}
	
	AID getPathFinderAID()
	{
		return pathFinderAID;
	}
	
		AID getAntColonyAID()
	{
		return antColonyAID;
	}
	
	public long getTickerTime(){return tickerTime;}
	public void incTickerTime(){tickerTime++;}

	public void inverseVisitedUrlStack()
	{
		Stack<URL> bufferVisitedUrl = new Stack<URL>();
		//System.out.println("DEBUG IN INVERSE STACK");
		//System.out.println("///////////////////////////////////////");
		//System.out.println("///////////////////////////////////////");
		while(!visitedUrl.empty())
		{
			//DEBUG
			//System.out.println(visitedUrl.peek());
			bufferVisitedUrl.push(visitedUrl.pop());
		}
		visitedUrl = bufferVisitedUrl;
		
	}


}
//END CLASS
